<template>
  <a-modal
    title="提交发货单"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="发货单号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input v-decorator="['orderNumber', {rules: [{required: true, message: '请输入发货单号！'}]}]"/>
        </a-form-item>
        <a-form-item
          label="发货备注"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input v-decorator="['remark', {rules: [{required: true, message: '请输入发货备注！'}]}]"/>
        </a-form-item>
        <a-form-item
          label="发货凭证"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input v-decorator="['file', {rules: [{required: true, message: '请输入发货凭证！'}]}]"
                   v-show="false"/>
          <FcUpload :file-list="fileList" @change="(value)=>form.setFieldsValue({file: value})"/>
        </a-form-item>
				<a-form-item
          label="发货方式"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input v-decorator="['delivery', {rules: [{required: true, message: '请输入发货方式！'}]}]"/>
        </a-form-item>

        <a-form-item>
					<a-radio-group button-style="solid" v-model="btnValue">
						<a-radio-button v-for="item in typeList" :key="item.value" :value="item.value">{{ item.label }}</a-radio-button>
					</a-radio-group>
					<a-button 
						size="default" 
						style="margin-left: 40px;" 
						@click="handleAddMaterial(
              btnValue==typeList[1].value ? listByMaterial.map(item=>item.materialId)
              : btnValue==typeList[2].value ? listByCable.map(item=>item.materialId)
              : btnValue==typeList[3].value ? listByPacking.map(item=>item.materialId)
              : []
            )" 
						icon="plus" 
						type="danger"
						:disabled="btnValue == typeList[0].value"
					>新增</a-button>
					<!-- 22--{{ filteredData }} -->
          <a-table
            ref="table"
            size="default"
            style="margin-bottom: 24px"
            :columns="btnValue==typeList[0].value ? columnsProduct : columnsOther"
            :data-source="
              btnValue==typeList[0].value ? filteredData 
              : btnValue==typeList[1].value ? listByMaterial 
              : btnValue==typeList[2].value ? listByCable 
              : btnValue==typeList[3].value ? listByPacking 
              : []"
            :pagination="false"
					>
            <template slot="remark" slot-scope="text, record">
              <a-input v-model:value="record.remark"/>
            </template>

            <template slot="storehousePositionRemark" slot-scope="text, record">
              <a-input v-model:value="record.storehousePositionRemark"/>
            </template>
            <!-- 发货数量（原料线缆包材） -->
            <template slot="number" slot-scope="text, record">
              <a-input-number 
                :min="0" 
                :max="record.inventoryNumber"
                style="width: 100%" 
                placeholder="请输入发货数量" 
                v-model:value="record.number"
              />
              <!-- <a-input v-model:value="record.storehousePositionRemark"/> -->
            </template>

						<template slot="action" slot-scope="text, record, index">
              <a @click="handleTableDelete(record, index)">删除</a>
            </template>

						<template slot="materialType" slot-scope="text, record, index">
              <span
								style="font-weight: bold;"
								:style="{color:
									record.materialType == '1473944069297156097' ? '#139ff0' : 
									record.materialType == '1473944389062504450' ? '#33dd33' : 
									record.materialType == '1473944715475824641' ? '#fc6d18' :
									record.materialType == '1501770962390024194' ? '#f04450' :
									'--'
								}"
							>{{ 
									record.materialType == '1473944069297156097' ? '原料' : 
									record.materialType == '1473944389062504450' ? '线缆' : 
									record.materialType == '1473944715475824641' ? '包材' :
									record.materialType == '1501770962390024194' ? '成品' :
									'--'
							}}</span>
            </template>

          </a-table>
        </a-form-item>
      </a-form>
    </a-spin>
		<select-material :typeList="typeList" @selected="handleSelected" ref="selectMaterialRef"/>
  </a-modal>
</template>

<script>
import {addAllType, addSimple, page} from '@/api/modular/main/emsorder/emsOrderManage'
import {sysDictDataSupplierList} from '@/api/modular/main/emssysdictdata/emsDictDataManage'
import FcUpload from '@/components/FCUpload/FcUploadPDF'
import {STable} from '@/components'
import SelectMaterial from './selectMaterial'
import {list as emsOrgList} from '@/api/modular/main/emsorg/emsOrgManage'

export default {
  components: {FcUpload, STable, SelectMaterial},
  data() {
    return {
			btnValue:'1473944318434619394',  //表格筛选按钮，默认成品
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 2}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
			typeList:[
				// {label:'全部', value:''},
				{label:'成品', value:'1473944318434619394'},
				{label:'原料', value:'1473944069297156097'},
				{label:'线缆', value:'1473944389062504450'},
				{label:'包材', value:'1473944715475824641'},
			],
      listByMaterial: [],  //原料列表数据
      listByCable:[], //线缆列表数据
      listByPacking:[], //包材列表数据
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      fileList: [],
      orderMaterials: [],
      orgIdSupplier: 'all',
      // supplierList: [],
      columnsProduct: [       // 成品
        {
          title: '序号', width:'80px',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '物料',
          dataIndex: 'materialName'
        },
				{
          title: '物料类型',
          dataIndex: 'materialType',
					scopedSlots: {customRender: 'materialType'},
        },
        {
          title: '料号',
          dataIndex: 'materialCode'
        },
        {
          title: '备注',
          dataIndex: '',
          scopedSlots: {customRender: 'remark'}
        },
        {
          title: '库位备注',
          dataIndex: '',
          scopedSlots: {customRender: 'storehousePositionRemark'}
        },
        {
          title: '发货数量',
          dataIndex: 'number'
        },
				// {
        //   title: '操作',
        //   dataIndex: '',
				// 	scopedSlots: {customRender: 'action'}
        // },
      ],
      columnsOther: [       // 原料、线缆、包材
        {
          title: '序号', width:'80px',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '物料名称',
          dataIndex: 'materialName'
        },
				{
          title: '物料类型',
          dataIndex: 'materialType',
					scopedSlots: {customRender: 'materialType'},
        },
        {
          title: '料号',
          dataIndex: 'materialCode'
        },
        {
          title: '发货数量',
          dataIndex: 'number',
          scopedSlots: {customRender: 'number'}
        },
        {
          title: '库存',
          dataIndex: 'inventoryNumber',
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
				{
          title: '操作',
          dataIndex: '',
					scopedSlots: {customRender: 'action'}
        },
      ],
    }
  },
  computed: {
    filteredData() {
      let orgIdSupplier = this.orgIdSupplier
      if (orgIdSupplier == 'all') {
        return this.orderMaterials
      }
      let filteredData
      if (orgIdSupplier == 'other') {
        let dictValues = this.supplierList.map(dict => dict.id)
        filteredData = this.orderMaterials.filter(value => {
          return dictValues.findIndex(value1 => value1 == value.orgIdSupplier) == -1
        })
      } else {
        filteredData = this.orderMaterials.filter(value => {
          return value.orgIdSupplier == orgIdSupplier
        })
      }
      return filteredData
    },
    supplierList() {
      return this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])
    }
  },
  methods: {
		handleTableDelete(row, index){
      if(this.btnValue==this.typeList[0].value){
        this.filteredData.splice(index, 1)
      }else if(this.btnValue==this.typeList[1].value){
        this.listByMaterial.splice(index, 1)
      }else if(this.btnValue==this.typeList[2].value){
        this.listByCable.splice(index, 1)
      }else if(this.btnValue==this.typeList[3].value){
        this.listByPacking.splice(index, 1)
      }
			
		},
		// 新增物料
		handleAddMaterial(arr){
			let selectList = arr
			this.$refs.selectMaterialRef.init(selectList, this.btnValue, '')
		},
		// 选择物料完成
		handleSelected(obj){
      if(obj.materialType == this.typeList[1].value){
			  this.listByMaterial.push(obj)
      }else if(obj.materialType == this.typeList[2].value){
			  this.listByCable.push(obj)
      }else if(obj.materialType == this.typeList[3].value){
			  this.listByPacking.push(obj)
      }
		},
    add(record) {
      if (!(record.selectedRows && record.selectedRows.length > 0)) {
        this.$message.error('请先选择物料!')
        return
      }
      this.visible = true
      // 设定订单类型
      setTimeout(() => {
        this.form.setFieldsValue(record)
        this.createOrderNumber()
      }, 100)
      // 创建简单订单(无单出入库)时,record中包含选择的物料
      this.orderMaterials.length = 0
      this.orderMaterials.push(...record.selectedRows)
    },
     // 打开弹框时候生成一个单号
    createOrderNumber(){
          var d = new Date()
          var year = d.getFullYear()
          var month = d.getMonth()
          month = month + 1 > 12 ? 1 : month + 1
          month =  month > 9 ? month : "0" +month.toString()
          var day = d.getDate()
          day = day > 9 ? day : "0" + day.toString()
          var hour = d.getHours()
          hour = hour > 9 ? hour : "0" + hour.toString()
          var minute = d.getMinutes()
          minute = minute > 9 ? minute : "0" + minute.toString()
          var second = d.getSeconds()
          second = second > 9 ? second : "0" + second.toString()

          let num = parseInt(Math.random()*100000).toString()
          // 如果随机数长度不够5位,则在后面补0,够5位为止
          for(let i=num.length; i<5; i++){ num+='0' }

          // let header = this.type==this.ORDER_TYPE_ENUM.inOrder.id?'WDRK': this.type==this.ORDER_TYPE_ENUM.outOrder.id?'WDCK': this.type==this.ORDER_TYPE_ENUM.purchaseOrder.id?'CG':''

          let scOrderNo = 'FH' + year+month+day+hour+minute+second + num

          this.form.setFieldsValue({orderNumber: scOrderNo})
    },
    handleSubmit() {
      const {form: {validateFields}} = this
      this.confirmLoading = true

      let errMaterial = this.listByMaterial.some(item => !item.number || item.number==0 || item.number>item.inventoryNumber )
      let errCable = this.listByCable.some(item => !item.number || item.number==0 || item.number>item.inventoryNumber )
      let errPacking = this.listByPacking.some(item => !item.number || item.number==0 || item.number>item.inventoryNumber )

      if(errMaterial || errCable || errPacking){
        this.confirmLoading = false
        return this.$message.error('发货数量不能为空 且 不能为0 且 不能大于库存!')
      }

      validateFields((errors, values) => {
        if (!errors) {
          // 将池中的物料记录转成订单物料记录
          let orderMaterials = this.orderMaterials.map(values => {
            let {materialPoolId, materialId, number, poolType, materialType, remark, status, createTime, createUser, updateTime, updateUser} = values
            return {
              materialId,
              number,
              remark,
              materialPoolId, //物料池ID，创建后删除用
            }
          })
          let listByMaterial = this.listByMaterial.map(values => {
            let {materialPoolId, materialId, number, remark} = values
            return {
              materialId,
              number,
              remark,
              materialPoolId, //物料池ID，创建后删除用
            }
          })
          let listByCable = this.listByCable.map(values => {
            let {materialPoolId, materialId, number, remark} = values
            return {
              materialId,
              number,
              remark,
              materialPoolId, //物料池ID，创建后删除用
            }
          })
          let listByPacking = this.listByPacking.map(values => {
            let {materialPoolId, materialId, number, remark} = values
            return {
              materialId,
              number,
              remark,
              materialPoolId, //物料池ID，创建后删除用
            }
          })
          // 物料池ID,便于创建订单后删除
          let parameter = Object.assign({
            orderType: this.$businessEnum.ORDER_TYPE_ENUM.deliverOrder.id,
            isOverseasStore: 'Y',
            orderMaterials: [...orderMaterials, ...listByMaterial, ...listByCable, ...listByPacking],
          }, values)
          addSimple(parameter).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('操作成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('操作失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.listByMaterial = []
      this.listByCable = []
      this.listByPacking = []
      this.fileList = []
			this.btnValue = this.typeList[0].value
    },
    // upload
    handleFileListStringChange(fileListString) {
      this.form.setFieldsValue({file: fileListString})
    },
  },
  created() {
  }
}
</script>
